package br.com.fiap.mercadinho.bean;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.common.ServiceException;
import br.com.fiap.mercadinho.dao.CustomerDAO;

@SuppressWarnings("serial")
public class Customer implements Serializable {

	private Integer id;
	private String name;
	private String cpfNumber;
	private Date birthDate;

	public Customer() {
		// TODO Auto-generated constructor stub
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setId(String id) {
		if (id != null && !id.equals("")) {
			this.id = Integer.valueOf(id);
		} else {
			this.id = 0;
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCpfNumber() {
		return cpfNumber;
	}

	public void setCpfNumber(String cpfNumber) {
		this.cpfNumber = cpfNumber;
	}

	public Date getBirthDate() {
		return birthDate;
	}

	public String getBirthDateString() {
		// if birthDate is null return blank string because the birthDate is
		// invalid format.
		if (this.birthDate == null)
			return "";

		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		return sdf.format(birthDate);
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	public void setBirthDate(String birthDate) {

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
			this.birthDate = sdf.parse(birthDate);
		} catch (ParseException e) {
			// if birth date is invalid set null value;
			this.birthDate = null;
		}

	}

	public String validateCustomer() throws ServiceException {
		if (this.name == null || this.name.equals(""))
			return "Campo nome e obrigatorio.";
		if (this.cpfNumber == null || this.cpfNumber.equals(""))
			return "Campo CPF e obrigatorio.";
		if (this.birthDate == null || getBirthDateString().length() != 10)
			// if birthDate length < 10 ex: 04/10/198 is invalid, set null.
			return "A data de nascimento deve estar no formato 'DD/MM/YYYY'";
		if (!isValidCPF()) {
			return "Ja existe um cliente cadastrado com o CPF informado.";
		}
		return "";
	}

	private boolean isValidCPF() throws ServiceException {
		try {
			CustomerDAO dao = new CustomerDAO();
			Customer customer = dao.findCustomerByCPF(cpfNumber);
			if (customer != null && !cpfNumber.equals(customer.getCpfNumber())) {
				return false;
			}
		} catch (DAOException e) {
			throw new ServiceException("Error in Customer validation: "
					+ e.getMessage());
		}
		return true;
	}

}
